<?php
/**
 * 用户模型
 * @author cjli
 *
 */
class UserModel extends Model
{
	/* 帐号变动类型 */
	const ACT_SAVING = 0;     // 帐户冲值
	const ACT_DRAWING = 1;     // 帐户提款
	const ACT_ADJUSTING = 2;   // 调节帐户
	const ACT_REFUND = 3;			//订单退款
	const ACT_PAY = 4;				//订单支付
	const ACT_SHARING = 5;    //订单分成
	const ACT_SHAIDAN = 6;    //晒单分成
	const ACT_OTHER = 99;     // 其他类型
	
	/**
	 * 会员等级列表
	 * @return Array
	 */
	public static function getRankList()
	{
		$rankList = array();
		if(S('user_rank_list')){
			$rankList = S('user_rank_list');
		}else{
			$rankdb = D('user_rank');
			$result = $rankdb->select();
			if($result){
				foreach ($result as $rank){
					$rankList[$rank['id']] = $rank; //ID为数组下标
				}
			}
			S('user_rank_list', $rankList);
		}
		return $rankList;
	}
	
	/**
	 * 更新会员等级
	 * @param int $uid 用户ID号
	 * @param int $rank_point 用户等级积分
	 * @return Array
	 */
	public static function updateUserRank($uid, $rank_point)
	{
		if(intval($uid)==0)
			return ;
		$rankId = 1;
		$rank_point = intval($rank_point);
		$rankList = self::getRankList();
		foreach ($rankList as $id => $rank){
			if($rank_point >= $rank['min_point'] && $rank_point < $rank['max_point']){
				$rankId = $id;break;
			}
		}
		$user_db = D('users');
		$user_db->where('id = '.$uid)->save(array('rank_id' => $rankId));
	}
	
	/**
	 * 获取用户信息
	 * @param int $uid 用户ID号
	 * @return Array
	 */
	public static function getUserInfo($uid)
	{
		$user_db = D('users');
		$userInfo = $user_db->find(intval($uid));
		if($userInfo && $userInfo['language_id']){
			$userInfo['language_name'] = SiteModel::getLanguageInfo($userInfo['language_id']);
		}
		return $userInfo;
	}
	
	/**
	 * 获取设计师列表
	 */
	public static function getUserDesignerList()
	{
		$userArray = array();
		$user_db = D('users');
		$user_db->field('id,nickname AS username,first_name,last_name');
		$userList = $user_db->where(array('is_designer' => 1, 'disabled' => 1))->select();
		if($userList){
			foreach ($userList as $user){
				$userArray[$user['id']] = $user;
			}
		}
		return $userArray;
	}
	/**
	 * 获取设计师信息
	 * @param int $user_id userID
	 */
	public static function getUserDesignerInfo($user_id)
	{
		$designer_db = D('user_designer');
		$designerInfo = $designer_db->where('user_id='.$user_id)->find();
		return $designerInfo ? $designerInfo : false;
	}
	
	/**
   * 产生用户散列密码
   * @param string $string 密码明文
   * @param string $rand_salt 随机加密码 
   * @return array 散列密码
   */
	public static function generatePassword($string, $rand_salt = null)
	{
		$md5password = md5($string);
		if(empty($rand_salt)){
			$rand_salt = rand(1, 9999);
		}
		$newpassword = md5($md5password . $rand_salt);
		return array($newpassword, $rand_salt);
	}
	
	/**
	 * 获取用户送货地址列表
	 * @param int $uid 用户ID号
	 * @return Array
	 */
	public static function getAddressList($uid)
	{
		$address_db = D('user_address');
		$addressList = $address_db->where('`user_id`='.$uid)->order('`default` DESC')->select();
		return $addressList ? $addressList : false;
	}
	
	/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   float   $frozen_money   冻结余额变动
 * @param   int     $rank_points    等级积分变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $change_desc    变动说明
 * @param   int     $change_type    变动类型：参见常量
 * @return  void
 */
	public static function logAccountChange($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = self::ACT_OTHER)
	{
		if(!intval($user_id))return false;
		$userInfo = self::getUserInfo($user_id);
		if(!$userInfo) return false;
		if(($user_money=='0.00' || $user_money=='0') && $rank_points=='0' && $pay_points=='0')return false;

		/* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => floatval($user_money),
        'frozen_money'  => floatval($frozen_money),
        'rank_points'   => floatval($rank_points),
        'pay_points'    => floatval($pay_points),
        'change_time'   => time(),
        'change_desc'   => $change_desc,
        'change_type'   => $change_type
    );
    $user_account_db = D('user_account_log');
    $user_account_db->add($account_log);


    /* 更新用户信息 */
    $sql = "UPDATE __TABLE__ ".
            " SET `user_money` = `user_money` + ('$user_money')," .
            " `frozen_money` = `frozen_money` + ('$frozen_money')," .
            " `rank_points` = `rank_points` + ('$rank_points')," .
            " `pay_points` = `pay_points` + ('$pay_points')" .
            " WHERE `id` = '$user_id'";
   	$user_db = D('users');
    $user_db->query($sql);

    
		//更新会员等级
		$userInfo = self::getUserInfo($user_id);
		self::updateUserRank($user_id, $userInfo['rank_points']);
	}
	
	/**
	 * 获取邮件模板信息
	 * @param string $path_alias 别名
	 * @param int $language_id 语言
	 */
	public static function getEmailTemplateInfo($path_alias, $language_id)
	{
		if(!intval($language_id)){
			$language_id = C('language_id');
		}
		$where = array(
			'path_alias' => $path_alias,
			'language_id' => $language_id,
		);
		$email_db = D('email_template_items');
		$email_db->field('title,content');
		$email_db->join('email_template ON email_template.id = email_template_items.email_template_id');
		$result = $email_db->where($where)->find();
		if(!$result){
			$where = array(
				'path_alias' => $path_alias,
				'language_id' => C('language_id'),
			);
			$email_db = D('email_template_items');
			$email_db->field('title,content');
			$email_db->join('email_template ON email_template.id = email_template_items.email_template_id');
			$result = $email_db->where($where)->find();
		}
		return $result;
	}

	/**
	 * 获取用户信息
	 * @param int $user_id 用户ID号
	 * @return Array
	 */
	public static function get_user_info($user_id)
	{
		$user_db = D('users');
		$userInfo = $user_db->find(intval($user_id));
		$userInfo['data'] = (isset($userInfo['data']) && $userInfo['data']) ? unserialize($userInfo['data']) : array();
		return $userInfo;
	}

	/**
	* 帐户变动
	* @param   int     $user_id        用户id
	* @param   float   $amount         变动金额
	* @param   int     $process_type   充值类型
	* @param   int     $is_paid        支付类型
	* @param   int     $paid_time      支付时间
	* @param   int     $admin_note     提示
	* @param   string  $user_note      提示
	* @return  bool
	*/
	public static function user_account_change($user_id, $amount, $process_type, $is_paid = 1, $paid_time = NULL, $admin_note = NULL, $user_note = NULL){
		
		if($paid_time == NULL){
			$paid_time = time();
		}   	    
		$amount_db = M('user_account');//充值日志
		$user_amount_data['user_id']   =  $user_id;
		$user_amount_data['add_time']  = time();
		$user_amount_data['paid_time'] = $paid_time;
		$user_amount_data['amount']    = $amount;
		$user_amount_data['process_type'] = $process_type; //类型为充值
		$user_amount_data['is_paid']      = $is_paid; //已完成支付
		if($admin_note) 
			$user_amount_data['admin_note'] = $admin_note;        
		if($user_note) 
			$user_amount_data['user_note']  = $user_note;
	
		return $amount_db->add($user_amount_data);
	}	

	/**
	* 记录帐户变动
	* @param   int     $user_id        用户id
	* @param   float   $user_money     可用余额变动
	* @param   float   $frozen_money   冻结余额变动
	* @param   int     $rank_points    等级积分变动
	* @param   int     $pay_points     消费积分变动
	* @param   string  $change_desc    变动说明
	* @param   int     $change_type    变动类型：参见常量
	* @return  void
	*/
	public static function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = self::ACT_OTHER)
	{
		if(!intval($user_id))return false;
		$userInfo = self::get_user_info($user_id);
		if(!$userInfo) return false;
		
		/* 插入帐户变动记录 */
		$account_log = array(
			'user_id'       => $user_id,
			'user_money'    => $user_money,
			'frozen_money'  => $frozen_money,
			'rank_points'   => $rank_points,
			'pay_points'    => $pay_points,
			'change_time'   => time(),
			'change_desc'   => $change_desc,
			'change_type'   => $change_type
		);
		$user_account_db = D('user_account_log');
		$user_account_db->add($account_log);
	
		/* 更新用户信息 */
		$sql = "UPDATE __TABLE__ ".
				" SET `user_money` = `user_money` + ('$user_money')," .
				" `frozen_money` = `frozen_money` + ('$frozen_money')," .
				" `rank_points` = `rank_points` + ('$rank_points')," .
				" `pay_points` = `pay_points` + ('$pay_points')" .
				" WHERE `id` = '$user_id'";
		$user_db = D('users');
		$user_db->query($sql);
		
		//更新会员等级
		$userInfo = self::get_user_info($user_id);
		self::updateUserRank($user_id, $userInfo['rank_points']);
	}
    //推荐好友返现
    public function get_money_friend($order_id,$user_email=""){
        if($user_email) {
            //判断此订单是否已经返余额
            if (!(D("email_invite_items")->where(array("order_id" => $order_id))->find())) {
                $invite_info = D("email_invite_items")->where("order_id =0 and fanxian_status=0 and invited_email='" . $user_email . "'")->order(" id desc")->limit(0, 1)->find();//echo (D("email_invite_items")->getLastSql());
                if ($invite_info) {
                    D("users")->query("update __TABLE__ set user_money=user_money+100 where id=" . $invite_info['user_id']);
                    //写入日志
                    $setsql['user_id'] = $invite_info['user_id'];
                    $setsql['user_money'] = 100;
                    $setsql['change_time'] = time();
                    $setsql['change_desc'] = "被邀请朋友订单满300返余额100";
                    $setsql['change_type'] = 5;
                    $setsql2['user_id'] = $invite_info['user_id'];
                    $setsql2['amount'] = 100;
                    $setsql2['add_time'] = time();
                    $setsql2['paid_time'] = time();
                    $setsql2['user_account'] = "被邀请朋友订单满300返余额100";
                    $setsql2['is_paid'] = 1;
                    if (D("user_account_log")->add($setsql) && D("user_account")->add($setsql2)) {
                        D('email_invite_items')->where("id=" . $invite_info['id'])->save(array('fanxian_status' => 1, "order_id" => $order_id));
                    }
                }
            }
        }
    }

}